<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>xv6 实验七 Multithreading | kiloGrand</title><meta name="keywords" content="xv6"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;thread.html  Uthread: switching between threads任务：在用户层面实现线程切换机制。 我们需要补充完整 user&#x2F;uthread.c 中的 thread_cre">
<meta property="og:type" content="article">
<meta property="og:title" content="xv6 实验七 Multithreading">
<meta property="og:url" content="https://kilogrand.gitee.io/2022/09/06/xv6-lab7/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;thread.html  Uthread: switching between threads任务：在用户层面实现线程切换机制。 我们需要补充完整 user&#x2F;uthread.c 中的 thread_cre">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2022-09-06T01:41:10.000Z">
<meta property="article:modified_time" content="2023-03-04T03:01:48.858Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="xv6">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2022/09/06/xv6-lab7/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'xv6 实验七 Multithreading',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-04 11:01:48'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">xv6 实验七 Multithreading</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-09-06T01:41:10.000Z" title="发表于 2022-09-06 09:41:10">2022-09-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-04T03:01:48.858Z" title="更新于 2023-03-04 11:01:48">2023-03-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="xv6 实验七 Multithreading"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><ul>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/schedule.html">https://pdos.csail.mit.edu/6.S081/2020/schedule.html</a></li>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/labs/thread.html">https://pdos.csail.mit.edu/6.S081/2020/labs/thread.html</a></li>
</ul>
<h2 id="Uthread-switching-between-threads"><a href="#Uthread-switching-between-threads" class="headerlink" title="Uthread: switching between threads"></a>Uthread: switching between threads</h2><p>任务：在用户层面实现线程切换机制。</p>
<p>我们需要补充完整 user/uthread.c 中的 thread_create() 和 thread_schedule()，以及 user/uthread_switch.S 中的 thread_switch。两个目标：</p>
<ul>
<li>当 thread_scheduler() 第一次跑某一线程时，该线程在自己的栈上执行传入的函数；</li>
<li>thread_switch 保存切换走的线程的寄存器，恢复要切换的线程的寄存器，并返回到线程上一次切走的位置。</li>
</ul>
<p>定义要保存的上下文</p>
<blockquote>
<p>寄存器被分为两种类型——caller-save 和 callee-save，顾名思义，前者要求调用者保存和恢复相关寄存器，而后者要求被调用者保存和恢复相关寄存器，<br>也就是说，从调用者的角度看，caller-save 寄存器在调用前后可能发生变化，而 callee-save 寄存器不会变化 。因此，切换时我们只需要保存和恢复 callee-save 寄存器。<br>除了 callee-save 寄存器需要保存和恢复以外，栈指针 sp 和返回地址 ra 也需要保存和恢复，它们构成了上述 context 结构体的内容。</p>
</blockquote>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// user/uthread/c</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">context</span> &#123;</span></span><br><span class="line">  uint64 ra;</span><br><span class="line">  uint64 sp;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// callee-saved</span></span><br><span class="line">  uint64 s0;</span><br><span class="line">  uint64 s1;</span><br><span class="line">  uint64 s2;</span><br><span class="line">  uint64 s3;</span><br><span class="line">  uint64 s4;</span><br><span class="line">  uint64 s5;</span><br><span class="line">  uint64 s6;</span><br><span class="line">  uint64 s7;</span><br><span class="line">  uint64 s8;</span><br><span class="line">  uint64 s9;</span><br><span class="line">  uint64 s10;</span><br><span class="line">  uint64 s11;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">thread</span> &#123;</span></span><br><span class="line">  <span class="type">char</span>       <span class="built_in">stack</span>[STACK_SIZE]; <span class="comment">/* the thread&#x27;s stack */</span></span><br><span class="line">  <span class="type">int</span>        state;             <span class="comment">/* FREE, RUNNING, RUNNABLE */</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">context</span> <span class="title">context</span>;</span>  <span class="comment">// thread context</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>参考 kernel/swtch.S，完成uthread_switch.S的上下文切换汇编<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">	.text</span><br><span class="line"></span><br><span class="line">	/*</span><br><span class="line">         * save the old thread&#x27;s registers,</span><br><span class="line">         * restore the new thread&#x27;s registers.</span><br><span class="line">         */</span><br><span class="line"></span><br><span class="line">	.globl thread_switch</span><br><span class="line">thread_switch:</span><br><span class="line">        /* YOUR CODE HERE */</span><br><span class="line">        sd ra, 0(a0)</span><br><span class="line">        sd sp, 8(a0)</span><br><span class="line">        sd s0, 16(a0)</span><br><span class="line">        sd s1, 24(a0)</span><br><span class="line">        sd s2, 32(a0)</span><br><span class="line">        sd s3, 40(a0)</span><br><span class="line">        sd s4, 48(a0)</span><br><span class="line">        sd s5, 56(a0)</span><br><span class="line">        sd s6, 64(a0)</span><br><span class="line">        sd s7, 72(a0)</span><br><span class="line">        sd s8, 80(a0)</span><br><span class="line">        sd s9, 88(a0)</span><br><span class="line">        sd s10, 96(a0)</span><br><span class="line">        sd s11, 104(a0)</span><br><span class="line"></span><br><span class="line">        ld ra, 0(a1)</span><br><span class="line">        ld sp, 8(a1)</span><br><span class="line">        ld s0, 16(a1)</span><br><span class="line">        ld s1, 24(a1)</span><br><span class="line">        ld s2, 32(a1)</span><br><span class="line">        ld s3, 40(a1)</span><br><span class="line">        ld s4, 48(a1)</span><br><span class="line">        ld s5, 56(a1)</span><br><span class="line">        ld s6, 64(a1)</span><br><span class="line">        ld s7, 72(a1)</span><br><span class="line">        ld s8, 80(a1)</span><br><span class="line">        ld s9, 88(a1)</span><br><span class="line">        ld s10, 96(a1)</span><br><span class="line">        ld s11, 104(a1)</span><br><span class="line">        </span><br><span class="line">        ret    /* return to ra */</span><br></pre></td></tr></table></figure></p>
<ul>
<li>在 thread_schedule() 中调用 uthread_switch 并把旧的线程上下文 &amp;t-&gt;context 和新的线程上下文 &amp;next_thread-&gt;context 作为参数传入；</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// user/uthread.c</span></span><br><span class="line"><span class="type">void</span> </span><br><span class="line"><span class="title function_">thread_schedule</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">thread</span> *<span class="title">t</span>, *<span class="title">next_thread</span>;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">/* Find another runnable thread. */</span></span><br><span class="line">  next_thread = <span class="number">0</span>;</span><br><span class="line">  t = current_thread + <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; MAX_THREAD; i++)&#123;</span><br><span class="line">    <span class="keyword">if</span>(t &gt;= all_thread + MAX_THREAD)</span><br><span class="line">      t = all_thread;</span><br><span class="line">    <span class="keyword">if</span>(t-&gt;state == RUNNABLE) &#123;</span><br><span class="line">      next_thread = t;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    t = t + <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (next_thread == <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;thread_schedule: no runnable threads\n&quot;</span>);</span><br><span class="line">    <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (current_thread != next_thread) &#123;         <span class="comment">/* switch threads?  */</span></span><br><span class="line">    next_thread-&gt;state = RUNNING;</span><br><span class="line">    t = current_thread;</span><br><span class="line">    current_thread = next_thread;</span><br><span class="line">    <span class="comment">/* YOUR CODE HERE</span></span><br><span class="line"><span class="comment">     * Invoke thread_switch to switch from t to next_thread:</span></span><br><span class="line"><span class="comment">     * thread_switch(??, ??);</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    thread_switch((uint64)&amp;t-&gt;context, (uint64)&amp;next_thread-&gt;context);</span><br><span class="line">  &#125; <span class="keyword">else</span></span><br><span class="line">    next_thread = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>最后，在 thread_create() 中把传入的函数指针给到线程上下文的 ra——这样当这个线程被调度执行时就可以执行指定函数了；同时把栈指针给到线程上下文的 sp——<strong>注意，栈空间是按地址从大到小增长的，</strong>所以我们给的应该是 stack 数组的末尾指针。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// user/uthread.c</span></span><br><span class="line"><span class="type">void</span> </span><br><span class="line"><span class="title function_">thread_create</span><span class="params">(<span class="type">void</span> (*func)())</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">thread</span> *<span class="title">t</span>;</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (t = all_thread; t &lt; all_thread + MAX_THREAD; t++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (t-&gt;state == FREE) <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  t-&gt;state = RUNNABLE;</span><br><span class="line">  <span class="comment">// YOUR CODE HERE</span></span><br><span class="line">  <span class="comment">// xyf</span></span><br><span class="line">  t-&gt;context.ra = (uint64)func;</span><br><span class="line">  t-&gt;context.sp = (uint64)t-&gt;<span class="built_in">stack</span> + STACK_SIZE - <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Using-threads"><a href="#Using-threads" class="headerlink" title="Using threads"></a>Using threads</h2><p>任务：在一台多核 Linux 或 MacOS 上使用 UNIX pthread 线程库写多线程的并行程序。</p>
<p>MIT 提供了一个代码 notxv6/ph.c，它开给定数量个线程，每个线程向 hash 表里面加许多 key（put 操作），然后从 hash 表里取出 key（get 操作），同时记录 put、get 的用时，以及缺失的 key——本来应该在 hash 表里，但是 get 不到。发生缺失的原因是 ph.c 没有在多线程时加锁，我们的任务就是把锁给加上。</p>
<p>相关接口：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">pthread_mutex_t</span> lock;            <span class="comment">// declare a lock</span></span><br><span class="line">pthread_mutex_init(&amp;lock, <span class="literal">NULL</span>); <span class="comment">// initialize the lock</span></span><br><span class="line">pthread_mutex_lock(&amp;lock);       <span class="comment">// acquire lock</span></span><br><span class="line">pthread_mutex_unlock(&amp;lock);     <span class="comment">// release lock</span></span><br></pre></td></tr></table></figure></p>
<p>给每个 hash 桶加一个锁，put 和 get 的时候先加锁，再操作，最后解锁就搞定了。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// notxv6/ph.c</span></span><br><span class="line"><span class="type">pthread_mutex_t</span> lock[NBUCKET];</span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">init_locks</span><span class="params">()</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; NBUCKET; i++)</span><br><span class="line">    assert(pthread_mutex_init(lock+i, <span class="literal">NULL</span>) == <span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> </span><br><span class="line"><span class="type">void</span> <span class="title function_">put</span><span class="params">(<span class="type">int</span> key, <span class="type">int</span> value)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">int</span> i = key % NBUCKET;</span><br><span class="line"></span><br><span class="line">  assert(pthread_mutex_lock(lock+i) == <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// is the key already present?</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">entry</span> *<span class="title">e</span> =</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> (e = table[i]; e != <span class="number">0</span>; e = e-&gt;next) &#123;</span><br><span class="line">    <span class="keyword">if</span> (e-&gt;key == key)</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(e)&#123;</span><br><span class="line">    <span class="comment">// update the existing key.</span></span><br><span class="line">    e-&gt;value = value;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// the new is new.</span></span><br><span class="line">    insert(key, value, &amp;table[i], table[i]);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  assert(pthread_mutex_unlock(lock+i) == <span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="keyword">struct</span> entry*</span><br><span class="line"><span class="title function_">get</span><span class="params">(<span class="type">int</span> key)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">int</span> i = key % NBUCKET;</span><br><span class="line"></span><br><span class="line">  assert(pthread_mutex_lock(lock+i) == <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">entry</span> *<span class="title">e</span> =</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> (e = table[i]; e != <span class="number">0</span>; e = e-&gt;next) &#123;</span><br><span class="line">    <span class="keyword">if</span> (e-&gt;key == key) <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  assert(pthread_mutex_unlock(lock+i) == <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> e;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">pthread_t</span> *tha;</span><br><span class="line">  <span class="type">void</span> *value;</span><br><span class="line">  <span class="type">double</span> t1, t0;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (argc &lt; <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;Usage: %s nthreads\n&quot;</span>, argv[<span class="number">0</span>]);</span><br><span class="line">    <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  nthread = atoi(argv[<span class="number">1</span>]);</span><br><span class="line">  tha = <span class="built_in">malloc</span>(<span class="keyword">sizeof</span>(<span class="type">pthread_t</span>) * nthread);</span><br><span class="line">  srandom(<span class="number">0</span>);</span><br><span class="line">  assert(NKEYS % nthread == <span class="number">0</span>);</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; NKEYS; i++) &#123;</span><br><span class="line">    keys[i] = random();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// initialize locks</span></span><br><span class="line">  init_locks();</span><br><span class="line">  ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Barrier"><a href="#Barrier" class="headerlink" title="Barrier"></a>Barrier</h2><p>任务：实现一个 barrier——执行到这里的线程必须等待，直到所有线程都执行到了这个地方。<br>和上一个任务一样，notxv6/barrier.c 已经写了一个不对的 barrier，它开给定数量个线程，每个线程做一个循环，循环的某处调用了 barrier()。我们期望所有线程都调用了 barrier() 之后才能继续执行。</p>
<p>相关接口：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">pthread_cond_wait(&amp;cond, &amp;mutex);  <span class="comment">// go to sleep on cond, releasing lock mutex, acquiring upon wake up</span></span><br><span class="line">pthread_cond_broadcast(&amp;cond);     <span class="comment">// wake up every thread sleeping on cond</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// notxv6/barrier.c</span></span><br><span class="line"><span class="type">static</span> <span class="type">void</span></span><br><span class="line"><span class="title function_">barrier</span><span class="params">()</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">// YOUR CODE HERE</span></span><br><span class="line">  <span class="comment">//</span></span><br><span class="line">  <span class="comment">// Block until all threads have called barrier() and</span></span><br><span class="line">  <span class="comment">// then increment bstate.round.</span></span><br><span class="line">  <span class="comment">//</span></span><br><span class="line">  assert(pthread_mutex_lock(&amp;bstate.barrier_mutex) == <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(++bstate.nthread == nthread)&#123;</span><br><span class="line">    assert(pthread_cond_broadcast(&amp;bstate.barrier_cond) == <span class="number">0</span>);</span><br><span class="line">    bstate.round++;</span><br><span class="line">    bstate.nthread = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">    assert(pthread_cond_wait(&amp;bstate.barrier_cond, &amp;bstate.barrier_mutex) == <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  assert(pthread_mutex_unlock(&amp;bstate.barrier_mutex) == <span class="number">0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="git-diff"><a href="#git-diff" class="headerlink" title="git diff"></a>git diff</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br></pre></td><td class="code"><pre><span class="line">diff --git a/answers-thread.txt b/answers-thread.txt</span><br><span class="line">new file mode 100644</span><br><span class="line">index 0000000..2b0e77f</span><br><span class="line">--- /dev/null</span><br><span class="line">+++ b/answers-thread.txt</span><br><span class="line">@@ -0,0 +1 @@</span><br><span class="line">+blablablablabla</span><br><span class="line">diff --git a/notxv6/barrier.c b/notxv6/barrier.c</span><br><span class="line">index 12793e8..0588d62 100644</span><br><span class="line">--- a/notxv6/barrier.c</span><br><span class="line">+++ b/notxv6/barrier.c</span><br><span class="line">@@ -30,7 +30,19 @@ barrier()</span><br><span class="line">   // Block until all threads have called barrier() and</span><br><span class="line">   // <span class="keyword">then</span> increment bstate.round.</span><br><span class="line">   //</span><br><span class="line">+  assert(pthread_mutex_lock(&amp;bstate.barrier_mutex) == 0);</span><br><span class="line">   </span><br><span class="line">+  <span class="keyword">if</span>(++bstate.nthread == nthread)&#123;</span><br><span class="line">+    // wake up every thread sleeping on “bstate.barrier_cond”</span><br><span class="line">+    assert(pthread_cond_broadcast(&amp;bstate.barrier_cond) == 0);</span><br><span class="line">+    bstate.round++;</span><br><span class="line">+    bstate.nthread = 0;</span><br><span class="line">+  &#125;</span><br><span class="line">+  <span class="keyword">else</span></span><br><span class="line">+    // go to <span class="built_in">sleep</span> on “bstate.barrier_cond”, releasing lock mutex, acquiring upon wake up</span><br><span class="line">+    assert(pthread_cond_wait(&amp;bstate.barrier_cond, &amp;bstate.barrier_mutex) == 0);</span><br><span class="line">+  </span><br><span class="line">+  assert(pthread_mutex_unlock(&amp;bstate.barrier_mutex) == 0);</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> static void *</span><br><span class="line">diff --git a/notxv6/ph.c b/notxv6/ph.c</span><br><span class="line">index 6df1500..a21c1c4 100644</span><br><span class="line">--- a/notxv6/ph.c</span><br><span class="line">+++ b/notxv6/ph.c</span><br><span class="line">@@ -17,6 +17,15 @@ struct entry *table[NBUCKET];</span><br><span class="line"> int keys[NKEYS];</span><br><span class="line"> int nthread = 1;</span><br><span class="line"> </span><br><span class="line">+// 给每个 <span class="built_in">hash</span> 桶初始化一个锁</span><br><span class="line">+pthread_mutex_t lock[NBUCKET];</span><br><span class="line">+void</span><br><span class="line">+init_locks()</span><br><span class="line">+&#123;</span><br><span class="line">+  <span class="keyword">for</span>(int i = 0; i &lt; NBUCKET; i++)</span><br><span class="line">+    assert(pthread_mutex_init(lock+i, NULL) == 0);</span><br><span class="line">+&#125;</span><br><span class="line">+</span><br><span class="line"> double</span><br><span class="line"> <span class="function"><span class="title">now</span></span>()</span><br><span class="line"> &#123;</span><br><span class="line">@@ -40,6 +49,8 @@ void put(int key, int value)</span><br><span class="line"> &#123;</span><br><span class="line">   int i = key % NBUCKET;</span><br><span class="line"> </span><br><span class="line">+  assert(pthread_mutex_lock(lock+i) == 0);</span><br><span class="line">+  </span><br><span class="line">   // is the key already present?</span><br><span class="line">   struct entry *e = 0;</span><br><span class="line">   <span class="keyword">for</span> (e = table[i]; e != 0; e = e-&gt;next) &#123;</span><br><span class="line">@@ -53,6 +64,8 @@ void put(int key, int value)</span><br><span class="line">     // the new is new.</span><br><span class="line">     insert(key, value, &amp;table[i], table[i]);</span><br><span class="line">   &#125;</span><br><span class="line">+  </span><br><span class="line">+  assert(pthread_mutex_unlock(lock+i) == 0);</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> static struct entry*</span><br><span class="line">@@ -60,12 +73,15 @@ get(int key)</span><br><span class="line"> &#123;</span><br><span class="line">   int i = key % NBUCKET;</span><br><span class="line"> </span><br><span class="line">-</span><br><span class="line">+  assert(pthread_mutex_lock(lock+i) == 0);</span><br><span class="line">+  </span><br><span class="line">   struct entry *e = 0;</span><br><span class="line">   <span class="keyword">for</span> (e = table[i]; e != 0; e = e-&gt;next) &#123;</span><br><span class="line">     <span class="keyword">if</span> (e-&gt;key == key) <span class="built_in">break</span>;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">+  assert(pthread_mutex_unlock(lock+i) == 0);</span><br><span class="line">+  </span><br><span class="line">   <span class="built_in">return</span> e;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line">@@ -115,6 +131,9 @@ main(int argc, char *argv[])</span><br><span class="line">     keys[i] = random();</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">+  // initialize locks</span><br><span class="line">+  init_locks();</span><br><span class="line">+  </span><br><span class="line">   //</span><br><span class="line">   // first the puts</span><br><span class="line">   //</span><br><span class="line">diff --git a/time.txt b/time.txt</span><br><span class="line">new file mode 100644</span><br><span class="line">index 0000000..f599e28</span><br><span class="line">--- /dev/null</span><br><span class="line">+++ b/time.txt</span><br><span class="line">@@ -0,0 +1 @@</span><br><span class="line">+10</span><br><span class="line">diff --git a/user/uthread.c b/user/uthread.c</span><br><span class="line">index 8e46826..29b3592 100644</span><br><span class="line">--- a/user/uthread.c</span><br><span class="line">+++ b/user/uthread.c</span><br><span class="line">@@ -10,16 +10,34 @@</span><br><span class="line"> <span class="comment">#define STACK_SIZE  8192</span></span><br><span class="line"> <span class="comment">#define MAX_THREAD  4</span></span><br><span class="line"> </span><br><span class="line">+struct context &#123;</span><br><span class="line">+  uint64 ra;  // <span class="built_in">return</span> addr</span><br><span class="line">+  uint64 sp;  // stack pointer</span><br><span class="line">+</span><br><span class="line">+  // callee-saved</span><br><span class="line">+  uint64 s0;</span><br><span class="line">+  uint64 s1;</span><br><span class="line">+  uint64 s2;</span><br><span class="line">+  uint64 s3;</span><br><span class="line">+  uint64 s4;</span><br><span class="line">+  uint64 s5;</span><br><span class="line">+  uint64 s6;</span><br><span class="line">+  uint64 s7;</span><br><span class="line">+  uint64 s8;</span><br><span class="line">+  uint64 s9;</span><br><span class="line">+  uint64 s10;</span><br><span class="line">+  uint64 s11;</span><br><span class="line">+&#125;;</span><br><span class="line"> </span><br><span class="line"> struct thread &#123;</span><br><span class="line">   char       stack[STACK_SIZE]; /* the thread<span class="string">&#x27;s stack */</span></span><br><span class="line"><span class="string">   int        state;             /* FREE, RUNNING, RUNNABLE */</span></span><br><span class="line"><span class="string">-</span></span><br><span class="line"><span class="string">+  struct context context;       // thread context</span></span><br><span class="line"><span class="string"> &#125;;</span></span><br><span class="line"><span class="string"> struct thread all_thread[MAX_THREAD];</span></span><br><span class="line"><span class="string"> struct thread *current_thread;</span></span><br><span class="line"><span class="string"> extern void thread_switch(uint64, uint64);</span></span><br><span class="line"><span class="string">-              </span></span><br><span class="line"><span class="string">+ </span></span><br><span class="line"><span class="string"> void </span></span><br><span class="line"><span class="string"> thread_init(void)</span></span><br><span class="line"><span class="string"> &#123;</span></span><br><span class="line"><span class="string">@@ -63,6 +81,7 @@ thread_schedule(void)</span></span><br><span class="line"><span class="string">      * Invoke thread_switch to switch from t to next_thread:</span></span><br><span class="line"><span class="string">      * thread_switch(??, ??);</span></span><br><span class="line"><span class="string">      */</span></span><br><span class="line"><span class="string">+    thread_switch((uint64)&amp;t-&gt;context, (uint64)&amp;next_thread-&gt;context);</span></span><br><span class="line"><span class="string">   &#125; else</span></span><br><span class="line"><span class="string">     next_thread = 0;</span></span><br><span class="line"><span class="string"> &#125;</span></span><br><span class="line"><span class="string">@@ -77,6 +96,9 @@ thread_create(void (*func)())</span></span><br><span class="line"><span class="string">   &#125;</span></span><br><span class="line"><span class="string">   t-&gt;state = RUNNABLE;</span></span><br><span class="line"><span class="string">   // YOUR CODE HERE</span></span><br><span class="line"><span class="string">+  t-&gt;context.ra = (uint64)func;</span></span><br><span class="line"><span class="string">+  // 栈空间是按地址从大到小增长的</span></span><br><span class="line"><span class="string">+  t-&gt;context.sp = (uint64)t-&gt;stack + STACK_SIZE - 1;</span></span><br><span class="line"><span class="string"> &#125;</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string"> void </span></span><br><span class="line"><span class="string">diff --git a/user/uthread_switch.S b/user/uthread_switch.S</span></span><br><span class="line"><span class="string">index 5defb12..70f2547 100644</span></span><br><span class="line"><span class="string">--- a/user/uthread_switch.S</span></span><br><span class="line"><span class="string">+++ b/user/uthread_switch.S</span></span><br><span class="line"><span class="string">@@ -8,4 +8,36 @@</span></span><br><span class="line"><span class="string"> 	.globl thread_switch</span></span><br><span class="line"><span class="string"> thread_switch:</span></span><br><span class="line"><span class="string"> 	/* YOUR CODE HERE */</span></span><br><span class="line"><span class="string">+        sd ra, 0(a0)</span></span><br><span class="line"><span class="string">+        sd sp, 8(a0)</span></span><br><span class="line"><span class="string">+        sd s0, 16(a0)</span></span><br><span class="line"><span class="string">+        sd s1, 24(a0)</span></span><br><span class="line"><span class="string">+        sd s2, 32(a0)</span></span><br><span class="line"><span class="string">+        sd s3, 40(a0)</span></span><br><span class="line"><span class="string">+        sd s4, 48(a0)</span></span><br><span class="line"><span class="string">+        sd s5, 56(a0)</span></span><br><span class="line"><span class="string">+        sd s6, 64(a0)</span></span><br><span class="line"><span class="string">+        sd s7, 72(a0)</span></span><br><span class="line"><span class="string">+        sd s8, 80(a0)</span></span><br><span class="line"><span class="string">+        sd s9, 88(a0)</span></span><br><span class="line"><span class="string">+        sd s10, 96(a0)</span></span><br><span class="line"><span class="string">+        sd s11, 104(a0)</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+        ld ra, 0(a1)</span></span><br><span class="line"><span class="string">+        ld sp, 8(a1)</span></span><br><span class="line"><span class="string">+        ld s0, 16(a1)</span></span><br><span class="line"><span class="string">+        ld s1, 24(a1)</span></span><br><span class="line"><span class="string">+        ld s2, 32(a1)</span></span><br><span class="line"><span class="string">+        ld s3, 40(a1)</span></span><br><span class="line"><span class="string">+        ld s4, 48(a1)</span></span><br><span class="line"><span class="string">+        ld s5, 56(a1)</span></span><br><span class="line"><span class="string">+        ld s6, 64(a1)</span></span><br><span class="line"><span class="string">+        ld s7, 72(a1)</span></span><br><span class="line"><span class="string">+        ld s8, 80(a1)</span></span><br><span class="line"><span class="string">+        ld s9, 88(a1)</span></span><br><span class="line"><span class="string">+        ld s10, 96(a1)</span></span><br><span class="line"><span class="string">+        ld s11, 104(a1)</span></span><br><span class="line"><span class="string">+        </span></span><br><span class="line"><span class="string"> 	ret    /* return to ra */</span></span><br><span class="line"><span class="string">+	</span></span><br><span class="line"><span class="string">+	</span></span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2022/09/06/xv6-lab7/">https://kilogrand.gitee.io/2022/09/06/xv6-lab7/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/xv6/">xv6</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/09/05/xv6-lab5/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">xv6 实验五 lazy page allocation</div></div></a></div><div class="next-post pull-right"><a href="/2022/09/07/xv6-lab8/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">xv6 实验八 locks</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/08/31/xv6-Chapter-0/" title="xv6 riscv book 中文版声明"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 riscv book 中文版声明</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-1/" title="xv6 第一章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第一章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-2/" title="xv6 第二章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第二章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-3/" title="xv6 第三章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第三章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-4/" title="xv6 第四章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第四章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-5/" title="xv6 第五章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第五章</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Uthread-switching-between-threads"><span class="toc-number">1.</span> <span class="toc-text">Uthread: switching between threads</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Using-threads"><span class="toc-number">2.</span> <span class="toc-text">Using threads</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Barrier"><span class="toc-number">3.</span> <span class="toc-text">Barrier</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git-diff"><span class="toc-number">4.</span> <span class="toc-text">git diff</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>